package com.zd.miko.tally.MVP.ModuleTallyList


import android.content.Context
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.GridLayoutManager
import android.text.InputType
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import com.zd.miko.tally.Bean.RealmBean.RealmTallyItem
import com.zd.miko.tally.Bean.TallyItemBean
import com.zd.miko.tally.MyApp.context
import com.zd.miko.tally.R
import io.realm.Realm
import kotlinx.android.synthetic.main.fragment_tally_list.*
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.UnsupportedEncodingException


/**
 * A simple [Fragment] subclass.
 */
class TallyListFragment : Fragment(), TallyListContract.View {

    private lateinit var listPresenter: TallyListPresenter

    private var mData: ArrayList<TallyItemBean> = ArrayList()

    private lateinit var keyboard: Keyboard

    private lateinit var customKeyboard: KeyboardView

    var adapter: ItemAdapter = ItemAdapter(mData)

    override fun setPresenter(presenter: TallyListContract.Presenter?) {
        this.listPresenter = presenter as TallyListPresenter
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater!!.inflate(R.layout.fragment_tally_list, container, false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initList()
        initKeyboard()
        initEvent()
    }


    private fun showSystemKeyboard(){
        customKeyboard.visibility = View.GONE
        openSystemKeyboard(ed_addition)
    }
    private fun showCustomKeyboard(){
        closeSystemKeyboard()
        ln_bottom.visibility = View.VISIBLE
        customKeyboard.visibility = View.VISIBLE
    }

    private fun initEvent() {
        tv_addition_hint.setOnClickListener{
            showSystemKeyboard()
        }
        ed_addition.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                showSystemKeyboard()
                return true
            }
        })

        ed_amount.inputType = InputType.TYPE_NULL

        ed_amount.setOnClickListener {
            showCustomKeyboard()
        }

    }



    private fun closeSystemKeyboard() {
        val view = activity.getWindow().peekDecorView()
        if (view != null) {
            val inputMethodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(view!!.getWindowToken(), 0)
        }
    }

    private fun openSystemKeyboard(view: EditText?) {
        activity.getWindow().getDecorView().postDelayed(Runnable {
            val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            view!!.requestFocus()
            imm.showSoftInput(view, 0)
        }, 100)
    }

    override fun initList() {
        initListData()
        recyclerView.adapter = adapter
        adapter.listener = ItemAdapter.clickListener { position -> showCustomKeyboard() }
        recyclerView.layoutManager = GridLayoutManager(this.context, 4)
    }

    override fun initListData() {
        //TODO
        addData()

        val realm = Realm.getDefaultInstance()
        val realmResult = realm.where(RealmTallyItem::class.java).findAll()
        for (r in realmResult) {
            val resId = getSelectorResource(r.resId)
            val tallyItemBean = TallyItemBean()
            tallyItemBean.itemName = r.name
            tallyItemBean.resId = resId
            mData.add(tallyItemBean)
        }
        adapter.notifyDataSetChanged()
    }

    private fun getSelectorResource(resName: String): Int {
        var resId = -123
        resId = context.resources.getIdentifier("category_e_$resName", "drawable", context.packageName)

        return resId
    }

    fun initKeyboard() {
        keyboard = Keyboard(context, R.xml.custom_keyboard)

        customKeyboard = custom_keyboard

        customKeyboard.keyboard = keyboard

        customKeyboard.isEnabled = true
        customKeyboard.isPreviewEnabled = false
        customKeyboard.setOnKeyboardActionListener(object : KeyboardView.OnKeyboardActionListener {
            override fun swipeRight() {}

            override fun swipeLeft() {}

            override fun swipeUp() {}

            override fun swipeDown() {}

            override fun onPress(primaryCode: Int) {}

            override fun onText(text: CharSequence?) {}

            override fun onRelease(primaryCode: Int) {}

            override fun onKey(primaryCode: Int, keyCodes: IntArray?) {

                if (primaryCode == -99) {
                    keyComplete()
                } else if (primaryCode == -5) {
                    keyDelete()
                }else{
                    val c = primaryCode.toChar()
                    insertChar(c)
                }

                Toast.makeText(context, "click:$primaryCode   $keyCodes   ", Toast.LENGTH_LONG).show()
            }
        })
    }

    private fun insertChar(c:Char) {
        val currentLength = ed_amount.editableText.length
        ed_amount.editableText.insert(currentLength,c.toString())
    }

    private fun keyDelete() {

    }

    private fun keyComplete() {

    }
}


/**
 * 以下测试
 */


/**
 * 初始化tally的条目存储到数据库中
 */
fun addData() {
    val realm = Realm.getDefaultInstance()
    //解析text文件
    realm.executeTransaction {
        realm.delete(RealmTallyItem::class.java)
    }

    try {
        //获取文件中的内容
        val inputStream = context.resources.openRawResource(R.raw.item_list)
        //将文件中的字节转换为字符
        val isReader = InputStreamReader(inputStream, "UTF-8")
        //使用bufferReader去读取字符
        val reader = BufferedReader(isReader)
        var out = reader.readLine()
        try {
            while (out != null) {
                val itemArray = out.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                realm.executeTransaction { realm1 ->
                    val item = realm.createObject(RealmTallyItem::class.java)
                    item.name = itemArray[0]
                    item.resId = itemArray[1]
                }
                out = reader.readLine()
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }

    } catch (e: UnsupportedEncodingException) {
        e.printStackTrace()
    }
}
